<?php
/**
 * RedCross Application
 *
 * @copyright Copyright (c) 2010, Kristian Stokke Tryggestad, Rune Vikestad, Andreas Flaten Wist, Simen Nicolai Echholt, Ole Henrik Jahren
 */

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
    public function __construct($application) {
        parent::__construct($application);

        Zend_Registry::set('upload_temp_path', APPLICATION_PATH . '/../data/tmp/');
        Zend_Registry::set('upload_final_path', APPLICATION_PATH . '/../public/static/uploads/');
    }

    /**
     * Setup the application log
     *
     * @return Zend_Log the logger object
     */
    protected function _initLog()
    {
    	$this->bootstrap('FrontController');
    	$log = new Zend_Log();

    	$writer = 'production' == $this->getEnvironment() ?
    	       new Zend_Log_Writer_Stream(APPLICATION_PATH . '/../data/logs/application.log') :
    	       new Zend_Log_Writer_Firebug();
        $log->addWriter($writer);

        if ('production' == $this->getEnvironment()) {
        	$filter = new Zend_Log_Filter_Priority(Zend_Log::CRIT);
        	$log->addFilter($filter);
        }

        // Alternatively:
        // $bootstrap = $this->getInvokeArg('bootstrap');
        // $log = $bootstrap->getResource('log');
        // where you want to access the log-object
        Zend_Registry::set('log', $log);
        return $log;
    }

    protected function _initConfig()
    {
        $this->bootstrap('FrontController');
        $config = $this->getOptions();
        Zend_Registry::set('config', $config);
    }

    /**
     * Setup the main applications autoloader
     *
     * @return Zend_Application_Module_Autoloader
     */
    protected function _initApplicationAutoload()
    {
        $this->bootstrap('log');
        $this->getResource('log')->debug('Bootstrapping ' . __METHOD__);

        $autoloader = new Zend_Application_Module_Autoloader(array(
            'namespace' => 'Core',
            'basePath'  => APPLICATION_PATH . '/modules/core',
        ));
        $autoloader->addResourceType('gateway', 'gateways/', 'Gateway');

        return $autoloader;
    }

    protected function _initCache()
    {
        // The Cachemanager takes care of the initialization
        $this->bootstrap('CacheManager');
        $cacheManager = $this->getResource('CacheManager');
        Zend_Registry::set('cacheManager', $cacheManager);
    }

    protected function _initPluginLoaderCache()
    {
        $config = $this->getOption('cache');
        if (!$config['enablePluginLoaderCache']) {
            return;
        }

        $this->bootstrap('log');
        $this->getResource('log')->debug('Bootstrapping ' . __METHOD__);

        $cacheFile = APPLICATION_PATH . '/../data/cache/pluginLoaderCache.php';
        if (file_exists($cacheFile)) {
            include_once $cacheFile;
        }
        Zend_Loader_PluginLoader::setIncludeFileCache($cacheFile);
    }

    protected function _initActionHelpers()
    {
        $this->bootstrap('log');
        $this->getResource('log')->debug('Bootstrapping ' . __METHOD__);

        Zend_Controller_Action_HelperBroker::addPath('RedCross/Controller/Helper', 'RedCross_Controller_Helper');
    }

    /**
     * Setup the ZFDebug debug bar
     */
    protected function _initZFDebug()
    {
        $this->bootstrap('log');
        $this->getResource('log')->debug('Bootstrapping ' . __METHOD__);

        $zfdebugConfig = $this->getOption('zfdebug');

        // Return if enabled option is not 1
        if (!isset ($zfdebugConfig['enabled']) || $zfdebugConfig['enabled'] != 1) {
            return;
        }

        // Ensure that Doctrine is loaded if we want Doctrine in the ZFDebug
        if (isset ($zfdebugConfig['plugins']['RedCross_Controller_Plugin_Debug_Plugin_Doctrine'])) {
            $this->bootstrap('Doctrine');
        }

        // Setup autoloader with namespace
        // This is not set in the .ini because we don't always need it
        $this->getApplication()->getAutoloader()->registerNamespace('ZFDebug_');

        $zfdebug = new ZFDebug_Controller_Plugin_Debug($zfdebugConfig);

        $this->bootstrap('FrontController');
        $frontController = $this->getResource('FrontController');
        $frontController->registerPlugin($zfdebug);
    }

    protected function _initRememberMe()
    {
        $this->bootstrap('FrontController');
        $frontController = $this->getResource('FrontController');
        $plug = new RedCross_Controller_Plugin_RememberMe();
        $frontController->registerPlugin($plug);
    }

    protected function _initSession()
    {
        $this->bootstrap('log');
        $this->getResource('log')->debug('Bootstrapping ' . __METHOD__);

        // For better resistance against Session Fixation
        $namespace = new Zend_Session_Namespace();
        if (!isset($namespace->initialized)) {
            Zend_Session::regenerateId();
            $namespace->initialized = true;
        }
    }

    protected function _initAcl()
    {
        $this->bootstrap('log');
        $log = $this->getResource('log');
        $log->debug('Bootstrapping ' . __METHOD__);

        $this->bootstrap('Doctrine');
        $this->bootstrap('CacheManager');
        $cacheManager = $this->getResource('CacheManager');
        $cache = $cacheManager->getCache('acl');

        if (!$acl = $cache->load('acl')) {
            $log->notice('ACL cache was not found.. Creating a fresh cache record');
            $acl = new RedCross_Acl();
            $cache->save($acl, null, array('acl', 'acl_object'));
        }
        $acl->initRole();
	    Zend_Registry::set('acl', $acl);
        return $acl;
    }

    protected function _initMailer()
    {
        $this->bootstrap('log');
        $this->getResource('log')->debug('Bootstrapping ' . __METHOD__);
        
        $options = $this->getOption('mailer');

        // Uncomment this to use SMTP
        $mailTransport = new Zend_Mail_Transport_Smtp($options['connection'], $options['transport']);
        Zend_Mail::setDefaultTransport($mailTransport);

        Zend_Mail::setDefaultFrom($options['sender'], $options['sender_name']);
    }

    protected function _initNavigation()
    {
        $this->bootstrap('log');
        $log = $this->getResource('log');
        $log->debug('Bootstrapping ' . __METHOD__);

        $this->bootstrap('LayoutHelper');
        $this->bootstrap('layout');
        $layout = $this->getResource('layout');
        $view = $layout->getView();

        // Caching
        $this->bootstrap('CacheManager');
        $cacheManager = $this->getResource('CacheManager');
        $cache = $cacheManager->getCache('navigation');

        $headNavigation = $cache->load('headNavigation');
        $mainNavigation = $cache->load('mainNavigation');
        $adminNavigation = $cache->load('adminNavigation');

        if (!$headNavigation || !$mainNavigation || !$adminNavigation) {
        	$config = new Zend_Config_Xml(APPLICATION_PATH . '/configs/navigation.xml');
        }

        if (!$headNavigation) {
            $log->notice('Head navigation cache was not found.. Creating a fresh cache record');
            $headNavigation = new Zend_Navigation($config->head);
            $cache->save($headNavigation, 'headNavigation', array('navigation', 'head_navigation'));
        }
        if (!$mainNavigation) {
            $log->notice('Main navigation cache was not found.. Creating a fresh cache record');
            $mainNavigation = new Zend_Navigation($config->navigation);
            $cache->save($mainNavigation, 'mainNavigation', array('navigation', 'main_navigation'));
        }
        if (!$adminNavigation) {
            $log->notice('Admin navigation cache was not found.. Creating a fresh cache record');
            $adminNavigation = new Zend_Navigation($config->admin);
            $cache->save($adminNavigation, 'adminNavigation', array('navigation', 'admin_navigation'));
        }

        Zend_Registry::set('headNavigation', $headNavigation);
        Zend_Registry::set('mainNavigation', $mainNavigation);
        Zend_Registry::set('adminNavigation', $adminNavigation);

        // Set default ACL and role for navigation
        $this->bootstrap('acl');
        $acl = $this->getResource('acl');
        Zend_View_Helper_Navigation_HelperAbstract::setDefaultAcl($acl);
        Zend_View_Helper_Navigation_HelperAbstract::setDefaultRole($acl->retrieveRole());
    }

    protected function _initTranslation()
    {
        $this->bootstrap('log');
        $translate = new Zend_Translate('array',APPLICATION_PATH . '/languages/errors-no.php','no');
        Zend_Validate_Abstract::setDefaultTranslator($translate);
    }

}

